<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export'" type="danger" size="small" @click="hExportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="doAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="Next" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="头像">
            <template v-slot="scope">
              <ImagerHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              {{ formateEmployess(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="doAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="doDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!--
            page-size当前的一页展示多少条数据
            current-change当页码发生变化时执行
            size-change当一页展示的数据个数发生变化时执行
           -->
          <el-pagination
            layout="total,sizes,prev, pager, next"
            :total="total"
            :page-size="size"
            :page-sizes="[2,5,10,20]"
            :current-page="page"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 弹框 -->
    <el-dialog :visible.sync="shouDialog" title="新增员工">
      <empDialog v-if="shouDialog" @doClose="doClose" />
    </el-dialog>
    <!-- 分配角色的弹框 -->
    <el-dialog :visible.sync="showDialogRole" title="分配角色">
      <assign-role v-if="showDialogRole" :cur-id="curId" @success="hSuccess" />
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, delEmp } from '@/api/employees'
import employees from '@/constant/employees'
import empDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'

const EMPLOYEE = employees.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})
export default {
  components: { empDialog, AssignRole },
  // 0.数据
  data() {
    return {
      // 0.1员工数据列表
      list: [],
      // 0.2分页的信息 page页码,size一页展示多少条数据
      page: 1,
      size: 10,
      // 0.3总条数
      total: 0,
      // 0.4弹框的布尔值
      shouDialog: false,
      // 0.5分配角色弹框
      showDialogRole: false,
      // 0.6传给子组件的id
      curId: ''
    }
  },
  // 1.created
  created() {
    // 1.1获取员工列表
    this.loadGetUseList()
  },
  // 2. 方法
  methods: {
    // 2.1获取员工列表
    async loadGetUseList() {
      const res = await getUserList({ page: this.page, size: this.size })
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 2.2聘用形式枚举
    formateEmployess(num) {
      return EMPLOYEE[num] || '未知'
    },
    // 2.3当页码发生变化时
    hCurrentChange(page) {
      this.page = page
      this.loadGetUseList()
    },
    // 2.4 当一页展示的条数发生变化时
    hSizeChange(size) {
      // 统一求第一页的数据
      this.page = 1
      this.size = size
      this.loadGetUseList()
    },
    // 2.5删除
    async doDel(id) {
      this.$confirm('请问您确定要删除吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        if (this.list.length === 1) {
          let page = this.page
          page--
          page = Math.max(1, page)
          this.page = page
        }
        await delEmp(id)
        this.$message.success('删除成功')
        this.loadGetUseList()
      }).catch(() => {
      })
    },
    // 2.6新增
    doAdd() {
      this.shouDialog = true
    },
    // 2.7子组件通知的事件
    doClose() {
      this.shouDialog = false
      // 跳转到最后一页
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadGetUseList()
    },
    // 2.8导出Excel
    async hExportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发送请求获取数据
        const res = await getUserList()
        const { data, header } = this.transFormData(res.data.rows)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '工资表   ', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 2.9导出格式转换
    transFormData(rows) {
      const header = Object.keys(rows[0])
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const headerZH = header.map(item => map[item])
      const data = rows.map(item => {
        return header.map(key => {
          if (key === 'formOfEmployment') {
            return EMPLOYEE[item[key]]
          } else {
            return item[key]
          }
        })
      })
      return { header: headerZH, data }
    },
    // 2.10解决排序问题
    Next(index) {
      const page = this.page
      const size = this.size
      return index + 1 + (page - 1) * size
    },
    // 2.11分配角色
    doAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 2.12子组件通知的事件
    hSuccess() {
      this.showDialogRole = false
    }
  }
}
</script>
